<?php
namespace app\common\controller;

use app\common\model\Gameulog;
use app\common\model\Player;
use think\Controller;
use think\Db;
use think\cache\driver\Redis;
use think\facade\Log;
use think\facade\Session;
use app\common\model\Gameagent;

/**
 * 后台公用基础控制器
 * Class AdminBase
 * @package app\common\controller
 */
class IndexBase extends Controller
{
    protected $game;
    protected $uid = 0;
    protected $cid = 0;
    protected $gid = 0;
    protected $token='';
    protected $account='';
    protected $player;
    protected $showFCM = 0;
    protected $channelName='';
    protected function initialize()
    {
        $data = $this->request->request();
        $route = $this->request->route();
        $data = array_merge($data, $route);
        if(empty($data['gid'])){
            echo "<script>alert('gid参数错误！')</script>";die();
        }
        $game = DB::connect('db_config_aiqi')->name('gamelist')
            ->whereIn('gstatus',[1,2])
            ->where(['id'=>$data['gid']])
            ->find();

        if(empty($game)){
            echo "<script>alert('游戏不存在！')</script>";die();
        }
        $this->gid = $game['id'];
        $this->game = $game;

        $action = $this->request->action();
        $params = $this->request->get();

        //推广id
        if(!empty($data['cid'])){
            $this->cid = $data['cid'] ?? 0;
            $channel = DB::connect('db_config_aiqi')->name('channel')->find($this->cid);
            if(empty($channel)){
                echo "<script>alert('渠道不存在！')</script>";die();
            }
            $this->channelName = ucfirst($channel['username']);
            //判断代理
            $channelGame = Gameagent::getInfo($this->cid,$this->gid);
            if(empty($channelGame) || $channelGame['status'] != 1){
                echo "<script>alert('游戏未审核！')</script>";die();
            }
            //分发渠道
//            $cid_arr = [5,6];
            if(!empty($route['cid'])){
//            if(!empty($route['cid']) && in_array($route['cid'], $cid_arr)){

                if(empty($params)){
                    echo "<script>alert('参数错误！')</script>";die();
                }
                // 动态加载自定义类（例如：app\common\CustomClass
                $className ="app\index\channel\\".$this->channelName; // 替换为你的类名
                if (!class_exists($className)) {
                    Log::info("渠道类初始化失败");
                }
                //自动注册
                $gameapi = new $className();
                $res = $gameapi->register($params,$this->gid,$this->cid);
                $this->token = $res['token'];

                if(!$res){
                    Log::info("渠道自动注册失败");die();
                }
            }
        }

        // 微信
        if(is_weixin()){
            // 判断登录
            if(!empty($data['code']) && !empty($data['state']) && $data['state'] == 'aiqi'){
                if(empty($data['token'])){
                    $player = $this->wxLogin();
                    $this->token = $player['token'];
                }
            }
        }
        if(!in_array($action,['login', 'register', 'phoneLogin','logout'])){
            $this->uid = $this->checkLogin();
            if(!$this->check_player_play_time()){
                $this->showFCM = 1;
            };
        }


        $this->assign('age_status',$this->player['is_age'] ?? 0);
        $this->assign('cid',$this->cid);
        $this->assign('uid',$this->uid);
        $this->assign('account',$this->account);
        $this->assign('token',$this->token);
        $this->assign('showFCM',$this->showFCM);
        parent::initialize();

    }

    protected function checkLogin(){
        $token = $this->request->param('token') ?? $this->token;

        $redis = new Redis();
        if($token){
            $player = $redis->get($token);
            if(!empty($player['account'])){
                $this->player = $player;
                $this->account = $player['account'];
                $this->uid = $player['id'];
                $this->token = $player['token'];
                return $this->uid;
            }
        }
    }

    /**
     * @param $sign 签名
     * @param $type 类型 默认1登录 2 支付
     * @return bool
     */
    protected function checkSign($data,$type = 1){
        if($type==1){
            $key = $this->game['login_key'];
        }else{
            $key = $this->game['pay_key'];
        }
        $sign = $data['sign'];
        unset($data['sign']);
        $check_sign = get_sign($data,$key);
        if($check_sign==$sign){
            return true;
        }
        return false;
    }

    protected function get_access_token($code){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx5f1a667410b75bdf&secret=a45a882920e857a2cfc6f01d6c67d337&code=$code&grant_type=authorization_code";
        $result = json_decode(file_get_contents($url),true);
        if(!empty($result['access_token'])){
            $redis = new Redis();
            $redis->set($code,$result, 7200);
            return $result;
        }
    }

    protected function get_snsapi_userinfo($code){
//        $data = get_access_token($code);
        $data = [
            'access_token'=>'93_KCN69Xr5uCfYwfdH_dDRY7qiog7uBG5ApB_dLF20uPBhVSi9TqDaGsJv-uvDuLYJ5NEDx0rIqahOBcnx_hn3fmAR2fSAYbqW_zT2iKrjcIs',
            'expires_in'=>'7200',
            'refresh_token'=>'93_FPVgR0Uk8UZ57BEXBGo0DIiF-6rf7hxiTaI8mJAR1ruFxWL4iDM-REfFXeKlkmtWL2g9w8iYMB5T2QmkuSccI324_zTQBTdJISXGoJC38Ug',
            'openid'=>'oxaxx6Jy07R44QgcZAAjea8WepXk',
            'scope'=>'snsapi_userinfo',
        ];
        $access_token = $data['access_token'];
        $openid = $data['openid'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $result = json_decode(file_get_contents($url),true);
        dump($result);exit;
    }

    // 微信登录
    protected function wxLogin()
    {
        $code = $this->request->param('code') ?? '';
        $token = $this->request->param('token') ?? '';
        if (empty($code)) {
            $this->error('code参数错误');
        }

        $redis = new Redis();

        // 判断code是否被使用
        if(!$redis->get($code)){
            $access_token = $this->get_access_token($code);
        }else {
            $access_token = $redis->get($code);
        }

        $where['account'] = 'wx_' . $access_token['openid'];
        $player = Player::getOne($where);

        if(!empty($token) && !empty($player)){
            return $redis->get($token);
        }
        $data['account'] = 'wx_'.$access_token['openid'];
        $data['password'] = get_encrypt('123456');
        $data['type'] = "2";
        $data['cid'] = $this->request->param('cid') ?? '';
        $data['gid'] = $this->request->param('gid') ?? '';
        if(empty($player)){
            //注册
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error('登录失败');
            }
        }

        $data['uid'] = $player['id'];

        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;

        unset($player['password']);
        //redis 保存用户信息
        $redis->set($token, $player);
        return $player;
    }


    /**
     * 防沉迷验证
     * @return bool
     */
    protected function check_player_play_time()
    {
        $palyer = $this->player;

        if(empty($palyer)){
            return true;
        }
        if($palyer['is_age'] == 0){
            return true;
        }
        if ($palyer['is_age'] == 2) { // 已成年
            return true;
        }
        // 未成年玩家只能在周五、周六、周日和法定节假日的20点到21点开始游戏
        $week = date('N', time());
        $hour = date('H', time());
        if(in_array($week,[5,6,7]) && $hour>=20 && $hour<=21 && is_hoilday()){
            return true;
        }
        return false;
    }



}